#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import json
import csv


def main():
    this_dir = os.path.dirname(os.path.realpath(__file__))
    trace_file = os.path.join(this_dir, "build.trace")
    csv_file = os.path.join(this_dir, "trace.csv")

    if not os.path.exists(trace_file):
        print("Error: Cannot find file {}".format(trace_file))
        return 1

    if os.path.exists(csv_file):
        os.remove(csv_file)
        print("File {} deleted successfully".format(csv_file))

    with open(trace_file, 'r') as f:
        data = json.load(f)

    print("Process trace to csv start...")

    row_list = []
    for item in data:
        name = item.get('name').replace(',', ';').replace(' ', '')
        if len(name) > 30000:
            name = name[0:30000]
        dur = item.get("dur")
        time_sec = float(dur) / 1000 / 1000
        time_minute = float(time_sec) / 60
        time_sec = format(time_sec, '.2f')
        time_minute = format(time_minute, '.2f')
        row_list.append([name, dur, time_sec, time_minute])

    with open(csv_file, 'w', encoding='utf-8', newline='') as rf:
        writer = csv.writer(rf)
        writer.writerow(['name', 'dur', 'time(second)', 'time(minute)', 'owner'])
        for item in row_list:
            writer.writerow(item)

    print("Process trace to csv finished.")


if __name__ == "__main__":
    sys.exit(main())
